package com.homer.gps.track;

import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnShowListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.homer.gps.track.adapters.PointsArrayAdaprer;
import com.homer.gps.track.adapters.StopsArrayAdapter;
import com.homer.gps.track.helper.TracksExporter;
import com.homer.gps.track.helper.TracksExporter.Export;
import com.homer.gps.track.helper.UsefullStaff;
import com.homer.gps.track.persist.PlaceModel;
import com.homer.gps.track.persist.Repository;
import com.homer.gps.track.persist.RouteModel;
import com.homer.gps.track.persist.StopModel;
import com.homer.gps.track.template.DefaultORMSherlockActivity;
import com.j256.ormlite.dao.ForeignCollection;

public class RouteDetail extends DefaultORMSherlockActivity {
	
	private int selected_id;
	private RouteModel selected_route = null;
	private ForeignCollection<StopModel> route_stops = null;
	
	private TextView routeStartPlace, routeStartDate, routeStartPlaceAddress, routeNote;
	private TextView routeEndPlace, routeEndDate, routeEndPlaceAddress;
	private ImageView routeStartPlaceTypeIcon;
	
	private ListView stopsList;
	private StopsArrayAdapter stopsListAdapter;

	private PointsArrayAdaprer routePointsListAdapter;
	private Repository repository = super.getRepository(this);
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);	
		setContentView(R.layout.route_detail);
			
		selected_id = getIntent().getIntExtra("id", -1);
		selected_route = repository.getRouteForId(selected_id);
		repository.getRouteForId(selected_id);
		
		initActivity();
	}
	
	protected void initActivity() {
		getSupportActionBar().setTitle(selected_route.getName().toString());
		//getSupportActionBar().setHomeButtonEnabled(true);
		//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setIcon(UsefullStaff.getRouteTypeImageResource(selected_route.getType()));
		
		routeNote = (TextView) findViewById(R.id.route_note);
		routeNote.setText(selected_route.getNote());
		
		routeStartPlace = (TextView) findViewById(R.id.start_place);
		routeStartPlaceAddress = (TextView) findViewById(R.id.start_place_address);
		routeStartDate = (TextView) findViewById(R.id.route_start_date);
		routeStartPlaceTypeIcon = (ImageView) findViewById(R.id.start_place_type_icon);
		routeEndPlace = (TextView) findViewById(R.id.end_place);
		routeEndPlaceAddress = (TextView) findViewById(R.id.end_place_address);
		routeEndDate = (TextView) findViewById(R.id.route_end_date);
		
		route_stops = selected_route.getStops();
		for (StopModel stop : route_stops) {
			if (stop.getType() == StopModel.STOP_TYPE_START) {
				routeStartDate.setText(UsefullStaff.getFormatedDateAndTime(stop.getStartDateTime(), "dd/MM/yyyy"));
				PlaceModel startPlace = null;
				try {
					startPlace = repository.lookupPlacesForStop(stop);
					if (startPlace != null) {
						routeStartPlace.setText(startPlace.getName());
						routeStartPlaceAddress.setText(startPlace.getParsedAddress());
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else if(stop.getType() == StopModel.STOP_TYPE_FINISH){
				routeEndDate.setText(UsefullStaff.getFormatedDateAndTime(stop.getEndDateTime(), "dd/MM/yyyy"));
				PlaceModel endPlace = null;
				try {
					endPlace = repository.lookupPlacesForStop(stop);
					if (endPlace != null) {
						routeEndPlace.setText(endPlace.getName());
						routeEndPlaceAddress.setText(endPlace.getParsedAddress());
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		stopsList = (ListView) findViewById(R.id.stops_list);
		List<StopModel> otherStops = null;
		try {
			otherStops = repository.lookupStopsForRoute(selected_route, StopModel.STOP_TYPE_OTHER);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (otherStops != null) {
			stopsListAdapter = new StopsArrayAdapter(this, R.layout.stops_list_item, otherStops);
		}
		
		stopsList.setAdapter(stopsListAdapter);
	}
	
	public void onShowOnMapClicked (View view) {
		Intent i = new Intent(this, MapActivity.class);
		i.putExtra("routeId", selected_id);
		startActivity(i);
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("Edit")
            .setIcon(R.drawable.edit)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        return true;
    }
	
	@Override
	public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
			switch (item.getItemId()) {
			case android.R.id.home:
				finish();
				break;
			case 0:
				Intent i = new Intent(this, RouteEdit.class);
				i.putExtra("id", selected_id);
				startActivity(i);
				break;
			default:
				break;
			}
		return true;

	}
		
	public void onExportClicked(View view) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.export_types, android.R.layout.simple_list_item_single_choice);
		alert.setTitle(R.string.export_menu_title);
		
		alert.setSingleChoiceItems(adapter, 1, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});
		
		alert.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				TracksExporter exporter = new TracksExporter(RouteDetail.this);
				String path = "";
				int selectedPosition = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
				if (selectedPosition == 0) {
					path = exporter.exportRoute(selected_route, Export.PDF);
				}else {
					path = exporter.exportRoute(selected_route, Export.TXT);
				}
				createIntent(path);
			}
		});
		
		alert.setNegativeButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.dismiss();
			}
		});

		AlertDialog dialog = alert.create();
		dialog.setOnShowListener(new OnShowListener() {

			@Override
			public void onShow(DialogInterface dialog) {
			}
		});
		dialog.show();
	}
	
	private void createIntent(String result) {
        createIntent(new String[]{result});
    }

    private void createIntent(String... result) {
        Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
        emailIntent.setType("message/rfc822");
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
        ArrayList<Uri> uris = new ArrayList<Uri>();
        for (String file : result)
        {
            Uri u = Uri.fromFile(new File(file));
            uris.add(u);
        }
        emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
        startActivity(Intent.createChooser(emailIntent, getString(R.string.export_menu_title)));
    }
}
